package com.example.loginsystem.service.impl;

import com.example.loginsystem.bean.MyUser;
import com.example.loginsystem.bean.Role;
import com.example.loginsystem.dao.MyUserDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Cheung0
 * Created on 2021/11/12
 */
@Component
public class UserQueryService implements UserDetailsService {

    @Autowired
    private MyUserDAO myUserDAO;

    /**
     * 取出用户
     *
     * @param username 用户名
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        MyUser myUser = null;
        try {
            myUser = myUserDAO.getByUsername(username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (myUser == null) {
            throw new UsernameNotFoundException("找不到用户！");
        }
        Set<GrantedAuthority> authorities = new HashSet<>();
        for (Role role : myUser.getRoles()) {
            System.out.println(role.getRoleName());
            authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
        }
        return new User(myUser.getUserName(),myUser.getPassword(),authorities);
    }

}
